package br.com.sgi.type;

import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.usertype.UserType;

import br.com.sgi.enuns.TipoRecadoEnum;

public class TipoRecadoType implements UserType{

	@Override
	public Object assemble(Serializable cached, Object owner)
			throws HibernateException {
		return cached;
	}

	@Override
	public Object deepCopy(Object value) throws HibernateException {
		return value;
	}

	@Override
	public Serializable disassemble(Object value) throws HibernateException {
		return (Serializable) value;
	}

	@Override
	public boolean equals(Object x, Object y) throws HibernateException {
		if (x == y) return true;
		if (x == null || y == null) return false;
		return x.equals(y);
	}

	@Override
	public int hashCode(Object x) throws HibernateException {
		return x.hashCode();
	}

	@Override
	public boolean isMutable() {
		return false;
	}

	@Override
	public Object nullSafeGet(ResultSet rs, String[] names, Object owner)
			throws HibernateException, SQLException {

		String value = rs.getString(names[0]);
		if (rs.wasNull() || value == null) {
			return null;
		}
		
		TipoRecadoEnum tpConsagracao = TipoRecadoEnum.getValue(value);
		return tpConsagracao;
	}

	
	@Override
	public void nullSafeSet(PreparedStatement st, Object value, int index)
			throws HibernateException, SQLException {
		
		if (value == null){
			//st.setNull(index, org.hibernate.type.StandardBasicTypes.STRING);
			st.setNull(index, Hibernate.STRING.sqlType());
		}else{
			TipoRecadoEnum setVal = (TipoRecadoEnum) value;
			st.setString(index, setVal.getCodigo());
		}
		
	}

	@Override
	public Object replace(Object original, Object target, Object owner)
			throws HibernateException {
		return original;
	}

	@Override
	@SuppressWarnings("unchecked")
	public Class returnedClass() {
		return Character.class;
	}

	@Override
	public int[] sqlTypes() {
		return new int[]{ Hibernate.STRING.sqlType() };
	}

}
